package com.taotao;



import com.taotao.observer1.MsgObServer;

import com.taotao.observer1.Observer;
import com.taotao.observer1.impl.MsgSubject;
import com.taotao.utils.ReflexUtils;
import com.taotao.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;

import org.reflections.Reflections;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Set;

/**
 * @Author: wangjin
 * @CreateTime: 2022-07-03  18:16
 */
@Slf4j
@Component
public class SpringBootInitialization  implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("springboot启动完成....");
        /**
         * 1.当我们springboot项目启动完成之后，获取当前有哪些观察者？ MsgObServer 所有实现class
         * 2.在根据该class去ioc容器中查找到该bean对象 存入到 msg主题中;
         */
        Set<Class> interfaceImpls = ReflexUtils.getInterfaceImpls(MsgObServer.class);
        MsgSubject msgSubject = SpringUtils.getBean("msgSubject", MsgSubject.class);
        interfaceImpls.forEach((c) -> {
            MsgObServer msgObServer = (MsgObServer) SpringUtils.getBean(c);
            msgSubject.addObserver((Observer) msgObServer);
        });
    }


    public static Set<Class> getInterfaceImpls(Class c) {
        Reflections reflections = new Reflections("com.taotao");
        //Filter是个接口，获取在指定包扫描的目录所有的实现类
        Set<Class> classes = reflections.getSubTypesOf(c);
        return classes;
    }
}

